package com.externalizable.demo2;

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 * 完整保存Externalizable对象的例子
 * 
 * @author Administrator
 *
 */
public class Blip3 implements Externalizable {

	private int i;
	private String s;// 没有初始化

	public Blip3() {
		System.out.println("Blip3 constructor");
	}

	public Blip3(String x, int a) {
		System.out.println("Blip3(String x, int a)");
		s = x;
		i = a;
		// s和i并不是在默认构造方法里初始化的
	}

	public String toString() {
		return s + i;
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		System.out.println("Blip3.readExternal");
		// 必须这么做
		s = (String) in.readObject();
		i = in.readInt() + 1;
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		System.out.println("Blip3.writeExternal");
		// 必须这么做，需要自己手动写入
		out.writeObject(s);
		out.writeInt(i);
	}

	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		Blip3 b3 = new Blip3("A String ", 47);
		System.out.println(b3);
		ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
				"blip3.out"));
		System.out.println("Save object:");
		o.writeObject(b3);
		o.close();

		ObjectInputStream in = new ObjectInputStream(new FileInputStream(
				"blip3.out"));
		Blip3 b4 = (Blip3) in.readObject();
		System.out.println(b4);
	}

}
